<?php

namespace common\components\form\field;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use common\components\Helper;
use common\components\form\Field;

/**
 * description of Template
 *
 * @author FireLoong
 */
class Template extends Field
{
    public function setup($options = [])
    {
        if ($this->setupParams) {
            $options = $this->setupParams[0] ?? $options;
        }
        //print_r($options);
        return $this;
    }

    public function xmlSetup(\SimpleXMLElement $field, $options = [])
    {
        $data = ArrayHelper::remove($options, 'data');
        $routeArray = explode('/', $data['route']);
        $app = Helper::runApp($data['client']);
        $routeCount = count($routeArray);
        $viewResPath = '/' . $routeArray[$routeCount - 2];

        if ($routeCount === 3) {
            $viewPath = $app->viewPath . $viewResPath;
            $viewThemePath = $app->basePath . $app->view->theme->baseUrl . $viewResPath;
        } else {
            $viewPath = dirname(dirname($data['path'])) . '/views' . $viewResPath;
            $viewThemePath = $app->getModule($routeArray[1])->viewPath . $viewResPath;
        }
        $action = $routeArray[$routeCount - 1];
        $viewFiles = array_map(function ($n) {
            return basename(substr($n, 0, -4));
        }, array_merge($this->_getViewFiles($viewPath, $action), $this->_getViewFiles($viewThemePath, $action)));
        $items = array_combine($viewFiles, $viewFiles);
        $options['inputOptions']['value'] = (string)$field->attributes()->default;
        $dropDownList = new DropDownList(array_merge([
            'model' => $this->model,
            'attribute' => $this->attribute . '[' . (string)$field->attributes()->name . ']',
            'form' => $this->form,
            'type' => 'dropDownList'
        ], $options));

        $label = Yii::t($data['langCat'], (string)$field->attributes()->label);
        $description = (string)$field->attributes()->description;
        $labelOptions = [];
        if (!empty($description)) {
            $labelOptions['desc'] = Yii::t($data['langCat'], $description);
        }

        return $dropDownList->setup($items, $this->setupParams)
            ->label($label, $labelOptions);
    }

    private function _getViewFiles($viewPath, $action)
    {
        $viewFiles = [];
        if (is_dir($viewPath)) {
            $viewFiles = FileHelper::findFiles($viewPath, ['only' => [$action . '_*.php']]);
            if (is_file($viewPath . '/' . $action . '.php')) {
                array_unshift($viewFiles, $viewPath . '/' . $action . '.php');
            }
        }
        return $viewFiles;
    }
}
